const { pool } = require("../db/index");
//创建连接池查询，开启事务锁保证多个sql操作同步完成或失败回滚
function connectionQuery(sqlArr, callback=()=>{}) {
  // console.log(sqlArr, "---");
  return new Promise((resolve, reject) => {
    var promiseArr = [];
    pool.getConnection(function (err, connection) {
      if (err) {
        return reject(err);
      }
      connection.beginTransaction((err) => {
        if (err) {
          connection.release(); // 释放链接
          return reject("开启事务失败");
        }
        // 将所有需要执行的sql封装为数组
        promiseArr = sqlArr.map((sql) => {
          return new Promise((resolve, reject) => {
            connection.query(sql, (e, rows, fields) => {
              if (e) {
                reject(e);
              } else {
                resolve(rows);
              }
            });
          });
        });
        // Promise调用所有sql，一旦出错，回滚，否则，提交事务并释放链接
        Promise.all(promiseArr)
          .then(async (res) => {
            connection.commit(async (error) => {
              if (error) {
                console.log("事务提交失败");
                connection.release(); // 释放链接
                reject(error);
              } else {
                connection.release(); // 释放链接
                if (callback) {
                  await callback();
                }
                resolve(promiseArr.length > 1 ? res : res[0]);
              }
            });
          })
          .catch((err) => {
            connection.rollback(() => {
              console.log("数据操作回滚", err, promiseArr.length);
              connection.release(); // 释放链接
              reject(err);
            });
          });
      });
    });
  });
}
module.exports = connectionQuery;
